import 'post_type.dart';

/// 动态模型类
/// 支持多种内容类型：纯文字、图文、文章、视频集
class PostModel {
  final String id;
  final String userId;
  final String username;
  final String? userAvatar;
  final PostType postType; // 动态类型
  final String? title; // 标题
  final String content; // 动态内容/摘要
  final String? coverUrl; // 封面图URL
  final String? summary; // 摘要/简介
  final List<String> images; // 图片列表（兼容旧版本）
  final String? videoUrl; // 视频URL（仅视频类型时有效）
  final String? location;
  final List<String> skillTags;
  final int likesCount;
  final int commentsCount;
  final int sharesCount;
  final int viewsCount; // 浏览数
  final bool isLiked;
  final bool isFollowed;
  final bool isHot; // 是否热门
  final String visibility; // 隐私设置：public-公开，private-私密，friends-仅好友可见
  final DateTime createdAt;
  final DateTime? updatedAt;

  PostModel({
    required this.id,
    required this.userId,
    required this.username,
    this.userAvatar,
    this.postType = PostType.text,
    this.title,
    required this.content,
    this.coverUrl,
    this.summary,
    this.images = const [],
    this.videoUrl,
    this.location,
    this.skillTags = const [],
    this.likesCount = 0,
    this.commentsCount = 0,
    this.sharesCount = 0,
    this.viewsCount = 0,
    this.isLiked = false,
    this.isFollowed = false,
    this.isHot = false,
    this.visibility = 'public',
    required this.createdAt,
    this.updatedAt,
  });

  factory PostModel.fromJson(Map<String, dynamic> json) {
    return PostModel(
      id: json['id']?.toString() ?? '',
      userId: json['user_id']?.toString() ?? '',
      username: json['username'] ?? '',
      userAvatar: json['user_avatar'],
      postType: _parsePostType(json['post_type']),
      title: json['title'],
      content: json['content'] ?? '',
      coverUrl: json['cover_url'],
      summary: json['summary'],
      images: (json['images'] as List<dynamic>?)
              ?.map((image) => image.toString())
              .toList() ??
          [],
      videoUrl: json['video_url'],
      location: json['location'],
      skillTags: (json['skill_tags'] as List<dynamic>?)
              ?.map((tag) => tag.toString())
              .toList() ??
          [],
      likesCount: json['likes_count'] ?? 0,
      commentsCount: json['comments_count'] ?? 0,
      sharesCount: json['shares_count'] ?? 0,
      viewsCount: json['views_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      isFollowed: json['is_followed'] ?? false,
      isHot: json['is_hot'] ?? false,
      visibility: json['visibility'] ?? 'public',
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'])
          : null,
    );
  }

  /// 解析动态类型
  static PostType _parsePostType(dynamic postType) {
    if (postType == null) return PostType.text;
    switch (postType.toString().toLowerCase()) {
      case 'text':
      case 'image': // 兼容旧数据
        return PostType.text;
      case 'article':
        return PostType.article;
      case 'video':
        return PostType.video;
      case 'video_collection':
        return PostType.videoCollection;
      case 'service':
        return PostType.service;
      default:
        return PostType.text;
    }
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'user_id': userId,
      'username': username,
      'user_avatar': userAvatar,
      'post_type': postType.name,
      'title': title,
      'content': content,
      'cover_url': coverUrl,
      'summary': summary,
      'images': images,
      'video_url': videoUrl,
      'location': location,
      'skill_tags': skillTags,
      'likes_count': likesCount,
      'comments_count': commentsCount,
      'shares_count': sharesCount,
      'views_count': viewsCount,
      'is_liked': isLiked,
      'is_followed': isFollowed,
      'is_hot': isHot,
      'visibility': visibility,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }

  PostModel copyWith({
    String? id,
    String? userId,
    String? username,
    String? userAvatar,
    PostType? postType,
    String? title,
    String? content,
    String? coverUrl,
    String? summary,
    List<String>? images,
    String? videoUrl,
    String? location,
    List<String>? skillTags,
    int? likesCount,
    int? commentsCount,
    int? sharesCount,
    int? viewsCount,
    bool? isLiked,
    bool? isFollowed,
    bool? isHot,
    String? visibility,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return PostModel(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      username: username ?? this.username,
      userAvatar: userAvatar ?? this.userAvatar,
      postType: postType ?? this.postType,
      title: title ?? this.title,
      content: content ?? this.content,
      coverUrl: coverUrl ?? this.coverUrl,
      summary: summary ?? this.summary,
      images: images ?? this.images,
      videoUrl: videoUrl ?? this.videoUrl,
      location: location ?? this.location,
      skillTags: skillTags ?? this.skillTags,
      likesCount: likesCount ?? this.likesCount,
      commentsCount: commentsCount ?? this.commentsCount,
      sharesCount: sharesCount ?? this.sharesCount,
      viewsCount: viewsCount ?? this.viewsCount,
      isLiked: isLiked ?? this.isLiked,
      isFollowed: isFollowed ?? this.isFollowed,
      isHot: isHot ?? this.isHot,
      visibility: visibility ?? this.visibility,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }
}

/// 文章模型类
/// 用于存储文章的详细内容
class ArticleModel {
  final String id;
  final String postId; // 关联的PostModel ID
  final String title; // 文章标题
  final String contentHtml; // HTML内容
  final int wordCount; // 字数
  final DateTime createdAt;
  final DateTime? updatedAt;

  ArticleModel({
    required this.id,
    required this.postId,
    required this.title,
    required this.contentHtml,
    this.wordCount = 0,
    required this.createdAt,
    this.updatedAt,
  });

  factory ArticleModel.fromJson(Map<String, dynamic> json) {
    return ArticleModel(
      id: json['id']?.toString() ?? '',
      postId: json['post_id']?.toString() ?? '',
      title: json['title'] ?? '',
      contentHtml: json['content_html'] ?? '',
      wordCount: json['word_count'] ?? 0,
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'post_id': postId,
      'title': title,
      'content_html': contentHtml,
      'word_count': wordCount,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }
}

/// 视频合集模型类
/// 用于存储视频合集信息
class VideoCollectionModel {
  final String id;
  final String postId; // 关联的PostModel ID
  final String title; // 合集标题
  final String? description; // 合集描述
  final String? coverUrl; // 合集封面
  final int videoCount; // 视频数量
  final DateTime createdAt;
  final DateTime? updatedAt;

  VideoCollectionModel({
    required this.id,
    required this.postId,
    required this.title,
    this.description,
    this.coverUrl,
    this.videoCount = 0,
    required this.createdAt,
    this.updatedAt,
  });

  factory VideoCollectionModel.fromJson(Map<String, dynamic> json) {
    return VideoCollectionModel(
      id: json['id']?.toString() ?? '',
      postId: json['post_id']?.toString() ?? '',
      title: json['title'] ?? '',
      description: json['description'],
      coverUrl: json['cover_url'],
      videoCount: json['video_count'] ?? 0,
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'post_id': postId,
      'title': title,
      'description': description,
      'cover_url': coverUrl,
      'video_count': videoCount,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }
}

/// 视频模型类
/// 用于存储单个视频信息
class VideoModel {
  final String id;
  final String collectionId; // 关联的VideoCollectionModel ID
  final String title; // 视频标题
  final String url; // 视频URL
  final String? coverUrl; // 视频封面
  final int? durationSec; // 视频时长（秒）
  final int orderNo; // 排序号
  final DateTime createdAt;
  final DateTime? updatedAt;

  VideoModel({
    required this.id,
    required this.collectionId,
    required this.title,
    required this.url,
    this.coverUrl,
    this.durationSec,
    this.orderNo = 0,
    required this.createdAt,
    this.updatedAt,
  });

  factory VideoModel.fromJson(Map<String, dynamic> json) {
    return VideoModel(
      id: json['id']?.toString() ?? '',
      collectionId: json['collection_id']?.toString() ?? '',
      title: json['title'] ?? '',
      url: json['url'] ?? '',
      coverUrl: json['cover_url'],
      durationSec: json['duration_sec'],
      orderNo: json['order_no'] ?? 0,
      createdAt: DateTime.parse(json['created_at']),
      updatedAt: json['updated_at'] != null
          ? DateTime.parse(json['updated_at'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'collection_id': collectionId,
      'title': title,
      'url': url,
      'cover_url': coverUrl,
      'duration_sec': durationSec,
      'order_no': orderNo,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt?.toIso8601String(),
    };
  }

  /// 格式化视频时长
  String get formattedDuration {
    if (durationSec == null) return '';
    final minutes = durationSec! ~/ 60;
    final seconds = durationSec! % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
}

class CommentModel {
  final String id;
  final String postId;
  final String userId;
  final String username;
  final String? userAvatar;
  final String content;
  final int likesCount;
  final bool isLiked;
  final DateTime createdAt;

  CommentModel({
    required this.id,
    required this.postId,
    required this.userId,
    required this.username,
    this.userAvatar,
    required this.content,
    this.likesCount = 0,
    this.isLiked = false,
    required this.createdAt,
  });

  factory CommentModel.fromJson(Map<String, dynamic> json) {
    return CommentModel(
      id: json['id'],
      postId: json['post_id'],
      userId: json['user_id'],
      username: json['username'],
      userAvatar: json['user_avatar'],
      content: json['content'],
      likesCount: json['likes_count'] ?? 0,
      isLiked: json['is_liked'] ?? false,
      createdAt: DateTime.parse(json['created_at']),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'post_id': postId,
      'user_id': userId,
      'username': username,
      'user_avatar': userAvatar,
      'content': content,
      'likes_count': likesCount,
      'is_liked': isLiked,
      'created_at': createdAt.toIso8601String(),
    };
  }
}
